<template>
  <div>
    <Category :sene="sene"></Category>
    <div v-show="sene==1">
      <el-card shadow="always" :body-style="{ padding: '20px' }" style="margin:10px 0px;">
        <div>
          <el-button
            type="primary"
            size="default"
            :icon="Plus"
            :disabled="cateStore.state.c3Id==''?true:false"
            @click="addAttr"
          >添加平台属性</el-button>
          <el-table border stripe style="margin:10px 0px 0px 0px" :data="tableData">
            <el-table-column label="序号" width="80" type="index"></el-table-column>
            <el-table-column label="属性名" width="90" prop="attrName"></el-table-column>
            <el-table-column label="属性值名称">
              <template #default="{row}">
                <el-tag
                  :type="choiceOne(attList)"
                  size="default"
                  v-for="(item,index) in row.attrValueList"
                  :key="index"
                  style="margin:0px 5px"
                >{{item.valueName}}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template #="{row}">
                <el-button type="warning" :icon="Edit" size="small" @click="updateAttr(row)"></el-button>
                <el-popconfirm
                  :title="`确定删除${row.attrName}?`"
                  confirmButtonText="确定"
                  cancelButtonText="取消"
                  confirmButtonType="danger"
                  cancelButtonType="text"
                  icon="ele-Delete"
                  width="200"
                  iconColor="#f00"
                  @confirm="delAttr(row)"
                  >
                  <template #reference >
                    <el-button type="danger" :icon="Delete" size="small"></el-button>
                  </template>
                </el-popconfirm>
              </template>
      
            </el-table-column>
          </el-table>
        </div>
      </el-card>
    </div>
    <div v-show="sene==2">
      <el-card shadow="always" :body-style="{ padding: '20px' }" style="margin:10px 0px;">
        <el-form label-width="80px" inline :model="addAttrParam" :rules="rules" ref="attrForm">
          <el-form-item label="属性名字" prop="attrName">
            <el-input placeholder="请你输入属性的名称" v-model="addAttrParam.attrName"></el-input>
          </el-form-item>
        </el-form>
        <el-button
          type="primary"
          :icon="Plus"
          :disabled="addAttrParam.attrName==''"
          @click="addAttrValue($refs)"
        >添加属性值</el-button>
        <el-button type="primary" @click="cancel">取消</el-button>
        <el-table border style="margin:10px 0px" :data="addAttrParam.attrValueList">
          <el-table-column label="序号" width="90" align="center" type="index"></el-table-column>
          <el-table-column label="属性值">
            <template #="{row,$index}">
              <el-input
                v-model="row.valueName"
                :ref="'a'+$index+'_Ref'"
                @blur="checkValueName(row,$index)"
                size="small"
                v-if="row.show"
              ></el-input>
              <div v-else @click="showInput(row,$refs,'a'+$index+'_Ref')" style="min-height:20px">{{ row.valueName}}</div>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #="{row,$index}">
              <el-popconfirm
              width="220"
              confirm-button-text="确定"
              cancel-button-text="取消"
              icon="ele-Delete"
              icon-color="#f00"
            :title="`确定删除${row.valueName}？`"
             confirm-button-type="danger"
              @confirm="delAttrValue($index)"
            >
              <template #reference>
                <el-button type="danger" :icon="Delete" size="small" ></el-button>
              </template>
            </el-popconfirm>
              
            </template>
          </el-table-column>
        </el-table>
        <el-button type="primary" @click="save" :disabled="addAttrParam.attrValueList.length==0">保存</el-button>
        <el-button type="primary" @click="cancel">取消</el-button>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
import useCategoryStore from '@/stores/category'
import { nextTick, reactive, ref, watch } from 'vue'

import { reqAttrInfoList, reqAttrAddOrUpdate, reqAttrDel } from '@/api/product/attr/index'
import { choiceOne } from './tool'
import { ElMessage,  } from 'element-plus'
import type { FormInstance,FormRules} from 'element-plus'
import type {tAddAttrParam,tAttrValue} from '@/api/product/attr/model/index'
import cloneDeep from 'lodash/cloneDeep'
const attList = ['success', 'info', 'warning', 'danger']
const cateStore = useCategoryStore()
const tableData = ref<tAddAttrParam[]>([])
const attrForm = ref<FormInstance>()
const checkAttrName = (rule: object, value: string, ok: Function) => {
  if (!/^[\u4e00-\u9fa5a-zA-Z0-9_-]{3,15}$/.test(value)) {
    ok(new Error('属性名格式有误'))
  } else {
    ok()
  }
}
const rules: FormRules = {
  attrName: [
    {required:true,trigger:'change',message:'此项是必填项'},
    {
      validator: checkAttrName,
      trigger: 'change',
    },
  ],
}

//监听仓库c3Id数据  发生变化重新请求数据
watch(
  () => cateStore.state.c3Id,
  async () => {
    if (cateStore.state.c3Id == '') {
      tableData.value = []
      return
    }
    getTableData()
  }
)
const getTableData = async () => {
  let id1 = cateStore.state.c1Id,
    id2 = cateStore.state.c2Id,
    id3 = cateStore.state.c3Id
  const result: tAddAttrParam[] = await reqAttrInfoList(id1, id2, id3)
  tableData.value = result
}

let addAttrParam = reactive<tAddAttrParam>({
  attrName: '', //属性名
  attrValueList: [], //属性列表值
  categoryId: '', //更改3级分类属性的Id
  categoryLevel: 3, //修改分类属性的等级
})
let sene = ref(1)
const addAttr = () => {
  attrForm.value?.resetFields()
  setTimeout(() => {
    addAttrParam.attrName = ''
    addAttrParam.attrValueList = []
    addAttrParam.categoryId = cateStore.state.c3Id as string
    sene.value = 2
  }, 0);

}
const addAttrValue = ($refs:any) => {
  if (addAttrParam.attrValueList.some((item: any) => item.valueName == '')) {
    return ElMessage({
      type: 'warning',
      message: '属性值不能为空',
    })
  }
  addAttrParam.attrValueList.push({
    valueName: '',
    show: true,
  })

  nextTick(()=>{
     let lastItem:any = reactive({})
     for (let item in $refs) {
       if(item.indexOf('Ref')!==-1){
         lastItem = $refs[item]
       }
     }
     lastItem.focus()
  })
}
const cancel = () => {
  sene.value = 1
}
const save = async () => {
  try {
    await attrForm.value?.validate()
    if (
    addAttrParam.attrValueList.some((item: any) => item.valueName.trim() == '')
  ) {
    return ElMessage({
      type: 'warning',
      message: '存在空值',
    })
  }
  try {
    await reqAttrAddOrUpdate(addAttrParam)
    ElMessage({
      type: 'success',
      message: addAttrParam.id ? '修改成功' : '添加成功',
    })
    sene.value = 1
    getTableData()
  } catch (error) {
    ElMessage({
      type: 'error',
      message: addAttrParam.id ? '修改失败' : '添加失败',
    })
  }
  } catch (error) {
     ElMessage({
      type:'error',
      message:'属性名格式不正确！'
     })
  }
   

}
const checkValueName = (row: tAttrValue, $index: number) => {
  if (row.valueName.trim() == '') {
    return ElMessage({
      type: 'warning',
      message: '属性值不能为空',
    })
  }
  if (
    addAttrParam.attrValueList.find((item: any) => {
      if (item != row) {
        return item.valueName == row.valueName
      }
    })
  ) {
    addAttrParam.attrValueList.splice($index, 1)
    return ElMessage({
      type: 'warning',
      message: '属性值不能重复',
    })
  }
  row.show = false
}
const delAttrValue = ($index: number) => {
  addAttrParam.attrValueList.splice($index, 1)
}

const showInput = (row: tAttrValue, dom: any, at: string) => {
  row.show = true
  nextTick(() => {
    dom[at].focus()
  })
}
const updateAttr = (row:tAddAttrParam)=>{
  sene.value=2
  Object.assign(
    addAttrParam,  
    cloneDeep(row)
  )
}
const delAttr = async(row:tAddAttrParam) =>{
  try {
    await reqAttrDel((row.id as number))
    ElMessage({
      type:'success',
      message:'删除成功'
    })
    getTableData()
  } catch (error) {
    ElMessage({
      type:'error',
      message:'删除失败'
    })
  }
  
}
</script>

<style scoped>
</style>